package com.kyxx.topics.activity;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kyxx.topics.BaseActivity;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.bean.ArticleDetailBean;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.Constants;
import com.kyxx.topics.utils.SettingUtils;
import com.kyxx.topics.utils.ToastUtils;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.request.BaseRequest;
import com.wang.avi.AVLoadingIndicatorView;

import org.json.JSONException;

import okhttp3.Call;
import okhttp3.Response;

public class DetailAdvertiseActivity extends BaseActivity {
    private ArticleDetailBean articleDetailBean;
    private WebView wv;
    private ImageView iv_back;
    private Button btn;
    private RelativeLayout rl_progress;
    private ProgressBar avi;
    private LinearLayout ll_reload;
    private String coupon_id;
    private SettingUtils settingUtils = new SettingUtils();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    rl_progress.setVisibility(View.GONE);
                    break;
                case 2:
                    rl_progress.setVisibility(View.VISIBLE);
                    break;
            }
        }
    };

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_detail_ad);
    }

    @Override
    protected void findViewById() {
        wv = (WebView) findViewById(R.id.wv);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        btn = (Button) findViewById(R.id.btn);
        rl_progress = (RelativeLayout) findViewById(R.id.rl_progress);
        avi = (ProgressBar) findViewById(R.id.avi);
        ll_reload = (LinearLayout) findViewById(R.id.ll_reload);
    }

    @Override
    protected void setListener() {
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                linQu();
            }
        });
    }

    @Override
    protected void processLogic() {
        WebSettings webSettings = wv.getSettings();
        wv.setWebViewClient(new DetailWebViewClient());
        webSettings.setCacheMode(Constants.WEB_CACHE);
        webSettings.setAppCacheEnabled(true);
        webSettings.setJavaScriptEnabled(true);// 设置支持javascript脚本
//        webSettings.setBuiltInZoomControls(true);// 设置支持缩放
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        wv.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
//        webSettings.setUseWideViewPort(true);// 图片被缩放后显示不全的问题
        //自适应屏幕
        wv.getSettings().setLoadWithOverviewMode(true);
        wv.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        switch (settingUtils.getZiTiDaXiao()) {
            case 0:
                wv.getSettings().setTextZoom(100);
                break;
            case 1:
                wv.getSettings().setTextZoom(125);
                break;
            case 2:
                wv.getSettings().setTextZoom(150);
                break;
        }
        getDetail();
    }

    public class DetailWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            rl_progress.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            handler.sendEmptyMessageDelayed(0, 0);
        }

    }

    private void getDetail() {
        HttpParams httpParams = new HttpParams();
        httpParams.put("uid", BaseApp.getModel().getId());
        httpParams.put("id", getIntent().getStringExtra("id"));
        String cachekey = "detail&uid=" + BaseApp.getModel().getId() + "&id=" + getIntent().getStringExtra("id");
        OkGoRequest.post(UrlUtils.DETAIL, DetailAdvertiseActivity.this, cachekey, CacheMode.REQUEST_FAILED_READ_CACHE, httpParams, new StringCallback() {
            @Override
            public void onBefore(BaseRequest request) {
                super.onBefore(request);
                rl_progress.setVisibility(View.VISIBLE);
                avi.setVisibility(View.VISIBLE);
                ll_reload.setVisibility(View.GONE);
            }

            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onCacheError(Call call, Exception e) {
                super.onCacheError(call, e);
                Message msg = new Message();
                msg.what = 2;
                handler.sendMessageDelayed(msg, Constants.DELAYTIMES);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    org.json.JSONObject result = new org.json.JSONObject(s);
                    articleDetailBean = JSON.parseObject(result.toString(), ArticleDetailBean.class);
//                    wv.loadData(articleDetailBean.getData().getContent(), "text/html; charset=UTF-8", null);//这种写法可以正确解码
                    wv.loadUrl(UrlUtils.BASEHTTP + articleDetailBean.getData().getUrl());
                    coupon_id=articleDetailBean.getData().getCoupon_id();
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void linQu() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uid", BaseApp.getModel().getId());
        jsonObject.put("nickname", BaseApp.getModel().getNickname());
        jsonObject.put("coupon_id", coupon_id);
        jsonObject.put("num", "1");
        HttpParams params = new HttpParams();
        params.put("json", jsonObject.toString());
        OkGoRequest.post(UrlUtils.TICKCOUPON, this, "ticket", CacheMode.NO_CACHE, params, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    org.json.JSONObject result = new org.json.JSONObject(s);
                    ToastUtils.show(context,result.getString("msg"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
